package org.jjche.core.util;


import org.jjche.common.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * <p>
 * 国际化
 * </p>
 *
 * @author miaoyj
 * @since 2024-07-01
 */
@Component
public class I18nUtil {

    private static MessageSource messageSource;

    public I18nUtil() {
    }

    /**
     * 通过set方法注入
     *
     * @param messageSource
     */
    @Autowired
    public void setMessageSource(MessageSource messageSource) {
        I18nUtil.messageSource = messageSource;
    }

    /**
     * 根据code获取国际化消息
     *
     * @param code code
     * @return
     */
    public static String getMessage(String code) {
        return messageSource.getMessage(code.toString(), null, code.toString(), LocaleContextHolder.getLocale());
    }

    /**
     * 通过code和占位符获取国际化消息
     *
     * @param code         消息code
     * @param messageCodes 占位符{}，不使用默认方式{0}
     * @return
     */
    public static String getMessage(String code, String... messageCodes) {
        String msg = messageSource.getMessage(code.toString(), null, code.toString(), LocaleContextHolder.getLocale());
        msg = StrUtil.format(msg, messageCodes);
        return msg;
    }
//    public static String getMessage(Object code, Object... messageCodes) {
//        Object[] objs = Arrays.stream(messageCodes).map(I18nUtil::getMessage).toArray();
//        return messageSource.getMessage(code.toString(), objs, code.toString(), LocaleContextHolder.getLocale());
//    }
}
